import { Injectable } from '@angular/core';
import { ipcRenderer, webFrame } from 'electron';
import * as childProcess from 'child_process';
import * as fs from 'fs';
import * as os from 'os';

@Injectable({
  providedIn: 'root',
})
export class ElectronService {
  ipcRenderer!: typeof ipcRenderer;
  webFrame!: typeof webFrame;
  childProcess!: typeof childProcess;
  fs!: typeof fs;
  os!: typeof os;

  constructor() {
    if (this.isElectron) {
      const electron = window.require('electron');
      this.ipcRenderer = electron.ipcRenderer;
      this.webFrame = electron.webFrame;
      this.childProcess = window.require('child_process');
      this.fs = window.require('fs');
      this.os = window.require('os');
    }
  }

  get homePath() {
    return window.process.env['HOME'] || ((window.process.env['HOMEDRIVE'] || '') + (window.process.env['HOMEPATH'] || ''));
  }

  get userDataDir() {
    if (!this.isElectron) {
      return undefined;
    }
    let args = window.process.argv;
    if (!args || args.length <= 1) {
      return undefined;
    }
    let result = args.find(s => s.indexOf('user-data-dir') > -1);
    if (!result) {
      return undefined;
    }
    return result.split('=')[1];
  }

  get isElectron(): boolean {
    return !!(window && window.process && window.process.type);
  }

  get saveList() {
    return undefined;
  }

  initFolder(path: string) {
    if (!this.fs.existsSync(path)) {
      this.fs.mkdirSync(path);
    }
  }

  exists(filename: string) {
    return this.fs.existsSync(filename);
  }

  write(filename: string, content: string) {
    this.fs.writeFileSync(filename, content);
  }

  read(filename: string) {
    return this.fs.readFileSync(filename, 'utf-8');
  }

  get mac() {
    let networkInterfaces: any = this.os.networkInterfaces();
    for (const i in networkInterfaces) {
      for (const j in networkInterfaces[i]) {
        if (networkInterfaces[i][j]['family'] === 'IPv4' && networkInterfaces[i][j]['mac'] !== '00:00:00:00:00:00' && networkInterfaces[i][j]['address'] !== '127.0.0.1') {
          return networkInterfaces[i][j]['mac'];
        }
      }
    }
  }
}
